<template>
  <div>
    <a-button @click="openModal">增加</a-button>
    <a-button @click="deleteId">删除</a-button>
    <a-table :columns="columns" :data-source="dataSource" :row-selection="rowSelection" :row-key="record => record.id"
      :scroll="{ y: 550 }" bordered class="editable-table">
      <template #bodyCell="{ column, text, record }">
        <template v-if="['violationOfDiscipline', 'deductionItem'].includes(column.dataIndex)">
          <div class="editable-cell">
            <a-input v-if="editableData[record.id]" v-model:value="editableData[record.id][column.dataIndex]"
              class="input-cell" />
            <template v-else>
              {{ text }}
            </template>
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'operation'">
          <div class="editable-row-operations">
            <span v-if="editableData[record.id]">
              <a-typography-link @click="save(record.id)">保存</a-typography-link>
              <a-popconfirm title="确定取消?" @confirm="cancel(record.id)" okText="确定" cancelText="取消">
                <a>取消</a>
              </a-popconfirm>
            </span>
            <span v-else>
              <a @click="edit(record.id)">编辑</a>
            </span>
          </div>
        </template>
      </template>
    </a-table>
    <BreakTheRuleAdd :open="isModalOpen" @update:open="isModalOpen = $event" @add="refreshData" />
  </div>
</template>

<script setup>
import { cloneDeep } from 'lodash-es';
import  BreakTheRuleAdd from '@/components/addBreakTheRule.vue'
import { onMounted, reactive, ref, computed } from 'vue';
import { getListBreak, batchDeleteBreakTheRule, deleteBreakTheRule, updateBreakTheRule } from '@/api/breakTheRuleApi';
const fetchData = () => {
  getListBreak().then(res => {
    dataSource.value = res.data;
  });
};
const refreshData = () => {
  fetchData();
};
const selectedRowKeys=ref([]);
const deleteId = () => {
  const selectedRows = dataSource.value.filter(item => selectedRowKeys.value.includes(item.id));
  console.log('即将删除的行:', selectedRows);

  if (selectedRows.length > 1) {
    // 如果选择的行数大于1，使用批量删除
    const selectedIds = selectedRows.map(item => item.id);
    console.log('批量删除学生 ID:', selectedIds);
    
    // 调用批量删除接口
    batchDeleteBreakTheRule(selectedIds)
      .then(results => {
        console.log('批量删除成功:', results);
        refreshData(); // 删除后刷新数据
      })
      .catch(error => {
        console.error('批量删除失败:', error);
      });
  } else if (selectedRows.length === 1) {
    // 如果只选择了一行，使用单个删除
    const selectedId = selectedRows[0].id;
    console.log(`正在删除学生 ID: ${selectedId}`);
    
    deleteBreakTheRule(selectedId)
      .then(results => {
        console.log('删除成功:', results);
        refreshData(); // 删除后刷新数据
      })
      .catch(error => {
        console.error('删除失败:', error);
      });
  } else {
    console.error('没有选择任何行进行删除');
  }
};
const isModalOpen = ref(false);

const openModal = () => {
  isModalOpen.value = true;
};

onMounted(() => {
  ListBrak();
})
const ListBrak = async () => {
  try {
    const res = await getListBreak();
    dataSource.value = res.data;
  } catch (error) {
    console.error('获取数据失败:', error);
  }
};
const columns = [
  {
    title: '学号',
    dataIndex: 'studentNumber',
    width: '20%',
  },
  {
    title: '违纪情况',
    dataIndex: 'violationOfDiscipline',
    width: '20%',
  },
  {
    title: '违纪扣分',
    dataIndex: 'deductionItem',
    width: '20%',
  },
  {
    title: '操作',
    dataIndex: 'operation',
  },
];

const data = [];

const dataSource = ref(data);
const editableData = reactive({});

const edit = id => {
  editableData[id] = cloneDeep(dataSource.value.find(item => id === item.id));
};

const save = id => {
  const updatedRecord = Object.assign(dataSource.value.find(item => id === item.id), editableData[id]);
  console.log(updatedRecord);

  // 调用接口更新学生信息
  updateBreakTheRule(updatedRecord)
    .then(() => {
      delete editableData[id];
      console.log('学生修改成功');
    })
    .catch(error => {
      console.error('学生修改失败:', error);
    });
};

const cancel = id => {
  delete editableData[id];
};
const rowSelection = ref({
  onChange: (keys, selectedRows) => {
    selectedRowKeys.value = keys; // 更新选中的行
    console.log(`selectedRowKeys: ${keys}`, 'selectedRows: ', selectedRows);
  },
  getCheckboxProps: record => ({
    disabled: record.name === 'Disabled User',
    name: record.name,
  }),
});

</script>

<style scoped>
.editable-row-operations a {
  margin-right: 8px;
}

.input-cell {
  margin: -5px 0;
}
</style>